package com.example.demo_upimg.upTextandImg;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/movements")
public class UpImgAndText3 {
    /**
     * 发布动态,从mongo sequence获取自增PID，再保存
     */
    @PostMapping
    public ResponseEntity movements(Movement movement,
                                    MultipartFile[] file) {
        //file这个名字要和前端页面一致，否则要额外注明。此处对应的前端为<input type="file" class="file" name="file" multiple="multiple"/><br/><br/>

        System.out.println("收到请求==");
        System.out.println("接收文本数据=" + movement);
        System.out.println("接收文件数据=" + file);

        Integer fileCount = 0;
        for (MultipartFile multipartFile : file) {
            System.out.println(multipartFile);
            if (multipartFile == null) {
                System.out.println("非文件");
            }
            String fileName = UUID.randomUUID() + multipartFile.getOriginalFilename();
            File dest = new File(new File("E:\\Zimg").getAbsolutePath() + "/" + fileName);
            if (!dest.getParentFile().exists()) {
                //新建空白图片
                dest.getParentFile().mkdirs();
            }
            try {
                //将图片流写入空白文件
                multipartFile.transferTo(dest); // 保存文件
                fileCount++;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        System.out.println("本次提交文件类型的个数==" + fileCount);
        return ResponseEntity.ok(null);
    }

}
